package com.leyou.auth.controller;

import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.entiy.UserInfo;
import com.leyou.auth.service.AuthService;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.utils.CookieUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@EnableConfigurationProperties(JwtProperties.class)
public class AuthController {

    @Autowired
    private AuthService authService;

    @Autowired
    private JwtProperties jwtProperties;

    //登录授权
    @PostMapping("accredit")
    public ResponseEntity<Void> authentication(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            HttpServletRequest request,
            HttpServletResponse response) {
        //登录校验
        String token = this.authService.authentication(username, password);
        if (StringUtils.isBlank(token)) {
            //若返回的token为空，证明没有查询到用户
            return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
        }
        // 将token写入cookie,并指定httpOnly为true，防止通过JS获取和修改
        CookieUtils.setCookie(request, response, jwtProperties.getCookieName(), token, jwtProperties.getCookieMaxAge(), null, true);
        return ResponseEntity.ok().build();
    }

    //验证用户信息,从cookie中存的token信息中取出用户信息
    //@CookieValue(XXX) 代表从cookie中取出key为XXX的值
    @GetMapping("verify")
    public ResponseEntity<UserInfo> verifyUser(
            @CookieValue("LY_TOKEN") String token,
            HttpServletRequest request,
            HttpServletResponse response) {
        try {
            UserInfo userInfo = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey());

            // 如果成功，我们还需要刷新token
            String newToken = JwtUtils.generateToken(userInfo,
                    jwtProperties.getPrivateKey(), jwtProperties.getExpire());
            // 然后写入cookie中
            // 将token写入cookie,并指定httpOnly为true，防止通过JS获取和修改
            CookieUtils.setCookie(request, response, jwtProperties.getCookieName(),
                    newToken, jwtProperties.getCookieMaxAge(), null, true);

            //若成功取出，则直接返回用户信息到前台
            return ResponseEntity.ok(userInfo);
        } catch (Exception e) {
            e.printStackTrace();
            // 抛出异常，证明token无效，直接返回401
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null);
        }
    }

    //退出登录
    @PostMapping("logOut")
    public ResponseEntity<Void> logOut(
            HttpServletRequest request,
            HttpServletResponse response) {
        try {
            UserInfo userInfo = null;


            //覆盖之前的cookie
            // 将token写入cookie,并指定httpOnly为true，防止通过JS获取和修改
            CookieUtils.setCookie(request, response, jwtProperties.getCookieName(),
                    null, 0, null, true);

            //若成功取出，则直接返回用户信息到前台
            return ResponseEntity.ok().build();

        } catch (Exception e) {
            e.printStackTrace();
            // 抛出异常，证明token无效，直接返回401
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null);
        }

    }
}
